<template>
  <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
    <a-row class="smart-query-form-row">
      <a-form-item label="岗位名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.postName" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button type="primary" @click="handleMenuClick">新增</a-button>
        <a-button type="primary" danger @click="handleDelete(null)">删除</a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.APPLICATIONMANAGEMENT.ID" :refresh="ajaxQuery" />
      </div>
    </a-row>
    <a-row :gutter="16" class="height100">
      <a-col :span="6">
        <a-card class="tree-container" size="small">
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            multiple
            :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
            :tree-data="treeData"
            :defaultExpandAll="true"
            @select="treeSelectChange"
          ></a-directory-tree>
        </a-card>
      </a-col>
      <a-col :span="18" class="height100">
        <a-table
          size="small"
          rowKey="id"
          :dataSource="tableData"
          :columns="columns"
          :pagination="false"
          :loading="tableLoading"
          bordered
          :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
          <template #bodyCell="{ column, record, text, index }">
            <template v-if="column.dataIndex === 'index'">
              {{ index }}
            </template>
            <template v-if="column.dataIndex === 'iconBase64'">
              <img :src="record.iconBase64" alt="" style="width: 40px" />
            </template>
            <template v-if="column.dataIndex === 'status'">
              <span v-if="record.status == 1">
                <check-circle-two-tone two-tone-color="#52c41a" />
              </span>
              <span v-else> </span>
            </template>
          </template>
          <template #operation="{ record }">
            <a-button size="small" style="margin-right: 10px" @click="upData(record)">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record)">删除</a-button>
          </template>
        </a-table>
        <div class="smart-query-table-page">
          <a-pagination
            showSizeChanger
            showQuickJumper
            show-less-items
            :pageSizeOptions="PAGE_SIZE_OPTIONS"
            :defaultPageSize="queryForm.pageSize"
            v-model:current="queryForm.pageNumber"
            v-model:pageSize="queryForm.pageSize"
            :total="total"
            @change="ajaxQuery"
            @showSizeChange="ajaxQuery"
            :show-total="(total) => `共${total}条`"
          />
        </div>
      </a-col>
    </a-row>
  </a-card>
  <ApplicationForm ref="applicationFormRef" @reload="ajaxQuery" />
</template>
    <script setup>
import { reactive, ref, onMounted, nextTick } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { useRouter } from 'vue-router';
import { smartSentry } from '/@/lib/smart-sentry';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import ApplicationForm from './components/form.vue';
import { configureApi } from '../../../api/system/configure-api.js';

// --------------------------- 表格 列 ---------------------------

const columns = ref([
  {
    title: '岗位编码',
    dataIndex: 'postCode',
  },
  {
    title: '岗位名称',
    dataIndex: 'postName',
  },
  {
    title: '部门编号',
    dataIndex: 'departmentId',
  },
  {
    title: '部门名称',
    dataIndex: 'department',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 150,
    slots: { customRender: 'operation' },
  },
]);

// --------------------------- 查询 ---------------------------

const queryFormState = {
  postName: '',
  description: '',
  pageSize: '',
  departmentId: '',
  pageNumber: 1,
  pageSize: PAGE_SIZE,
  pageSizeOptions: 50,
};
const queryForm = reactive({ ...queryFormState });
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

// 日期选择
const searchDate = ref();

function dateChange(dates, dateStrings) {
  queryForm.startTime = dateStrings[0];
  queryForm.endTime = dateStrings[1];
}
// 查询
function onSearch() {
  queryForm.pageNumber = 1;
  ajaxQuery();
}
// 重置查询
function resetQuery() {
  searchDate.value = [];
  Object.assign(queryForm, queryFormState);
  ajaxQuery();
}
function dateToSeconds(dateStr) {
  if (dateStr == '') {
    return '';
  }
  let date = new Date(dateStr);
  return date.getTime() / 1000;
}
// 列表数据获取
async function ajaxQuery() {
  try {
    let responseModel = await configureApi.fetchPosts(queryForm);
    const list = responseModel.data.rows;
    total.value = responseModel.data.records;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

const expandedKeys = ref(['1', '1-2']);
const selectedKeys = ref([]);
const treeData = ref([]);
// 查询部门列表并构建 部门树
async function queryDepartmentTree() {
  let res = await configureApi.getOrgsTree();
  nextTick(() => {
    treeData.value = buildTree(res.data.nodes);
  });
}
function treeSelectChange(idList,info) {
  const stringId = idList.join('');
  queryForm.departmentId = stringId;
  queryForm.postName = info.node.title;
  ajaxQuery();
}

function buildTree(data) {
  const tree = [];
  const map = {};
  // 先把所有节点放入一个映射表
  data.forEach((item) => {
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });

  // 构建树
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      // 如果是根节点
      tree.push(map[item.key]);
    } else {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}

// --------------------------- 增加、修改、详情 ---------------------------

let router = useRouter();
const applicationFormRef = ref(null);
function handleMenuClick() {
  applicationFormRef.value.showDrawer(null, 1, '新增',queryForm);
}
async function upData(record) {
  let res = await configureApi.getPosts(record.id);
  applicationFormRef.value.showDrawer(res.data, 0, '编辑');
}

function handleDelete(value) {
  Modal.confirm({
    title: () => '确定要删除吗?',
    content: () => '删除后不可恢复',
    onOk() {
      let ids;
      if (value) {
        //判断value 是否为多个删除
        ids = value.id;
      } else {
        ids = Object.values(selectedRowKeyList.value).join(',') + ',';
      }
      configureApi.deletePosts(ids).then((res) => {
        if (res.code === 0) {
          message.success('删除成功！');
          ajaxQuery();
        }
      });
    },
    onCancel() {},
  });
}

// 获取分类下拉
const FindList = ref([]);
async function getFindList() {
  try {
    let res = await applicationManagementApi.queryFindList();
    FindList.value = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    FindList.value.unshift({ label: 'ALL', value: '' });
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}
// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}
onMounted(() => {
  ajaxQuery();
  queryDepartmentTree();
});
</script>